import { _pick, reduceToObject } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createStoreApiMWRouter } from "../../middleware/store-api/storeOwnerChecker";
import pageMW from "../../middleware/pager";
import {
  listStoreFanWithUserAndUserStats,
  updateStoreFan,
} from "../../service/storeFanService";
import { listAggsToUserRecentNewses } from "../../service/userPvLogService";
const router = createStoreApiMWRouter();

router.get(
  "store-fans",
  "/sto/:storeId/fans",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { storeId } = ctx.params;
    let { keyword } = ctx.query;
    const { userId, limit, offset, ts } = ctx;

    const { total, items } = await listStoreFanWithUserAndUserStats(
      { storeId, keyword },
      {
        limit,
        offset,
        ts,
      }
    );
    const followerRecentNews = await listAggsToUserRecentNewses(
      items.map((it) => it.followerUserId)
    );
    const recentNewsMap = reduceToObject(
      followerRecentNews,
      (o) => o.userId,
      (o) => o.latestTime
    );

    ctx.body = {
      total,
      rows: items.map((it) => ({
        recentNews: recentNewsMap[it.followerUserId],
        ..._pick(
          it,
          "storeFanId",
          "aliasName",
          "followerUserNickName",
          "followerUserPic",
          "involveActivityCount",
          "viewCount",
          "payAmount"
        ),
      })),
    };
  }
);

// 备注粉丝名称
router.put("/sto/:storeId/fan/:brandFanId/alias", async (ctx: AppCTX, next) => {
  const { storeId, storeFanId } = ctx.params;
  const { aliasName } = ctx.request.body;
  const { userId } = ctx;

  const storeFan = await updateStoreFan({ storeFanId, aliasName });

  ctx.body = {
    ..._pick(storeFan, "storeFanId", "aliasName"),
  };
});

export default router;
